package slidingWindowAlgorithm.review4_20;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Class438 {

    public List<Integer> findAnagrams(String s, String p) {

        ArrayList<Integer> list = new ArrayList<>();
        HashMap<Character, Integer> need = new HashMap<>();
        for (char a : p.toCharArray()) {
            need.put(a, need.getOrDefault(a, 0) + 1);
        }
        HashMap<Character, Integer> window = new HashMap<>();
        int left = 0, right = 0;
        int start = 0;
        int valid = 0;
        int size = s.length();
        int minLen = size + 1;
        while (right < size) {
            char c = s.charAt(right);
            right++;
            if (need.containsKey(c)) {
                window.put(c, window.getOrDefault(c, 0) + 1);
                if (need.get(c).equals(window.get(c))) {
                    valid++;
                }
            }
            int needlength = p.length();
            int needSize = need.size();
            while (needSize == valid) {
                if (right - left == needlength) {
                    list.add(left);
                }
                c = s.charAt(left);
                left++;
//  CKG TODO 2023/4/20:  if  双重验证 首先是否包含字符c  然后字符c的个数是否是需要的个数 两者否满足了再 valid--
                if (need.containsKey(c)) {
                    if(window.get(c).equals(need.get(c)))
                        valid--;
                    window.put(c, window.get(c) - 1);
                }
            }

        }
        return list;
    }

    public static void main(String[] args) {

       Class438 class438 = new Class438();
//        System.out.println(class438.findAnagrams("cbaebabacd", "abc"));
        List<Integer>  list= class438.findAnagrams("cbaebabacd", "abc");
        for (int a:list) {
            System.out.println(a);
        }


    }

}
